package com.hulu.yec.sys.user.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.hulu.yec.common.Constant;
import com.hulu.yec.common.PageModel;
import com.hulu.yec.common.util.FastjsonUtil;
import com.hulu.yec.common.util.LogUtil;
import com.hulu.yec.sys.user.entity.SearchCondition;
import com.hulu.yec.sys.user.entity.SysUserEntity;
import com.hulu.yec.sys.user.service.SysUserDao;

/**
 * 系统管理之用户管理控制层
 * 
 * @author hf 2016年3月9日
 */
@WebServlet("/user/AllUserCommandServlet")
public class AllUserCommandServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final SysUserDao sysDao = new SysUserDao();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding(Constant.ENCODING_UTF8);
		String command = request.getParameter("command");
		if ("splitList".equals(command)) {
			splitList(request, response);
		} else if ("changeState".equals(command)) {
			changeState(request, response);
		} else if ("getUserInfo".equals(command)) {
			getUserInfo(request, response);
		} else if ("toAddUser".equals(command)) {
			toAddUser(request, response);
		} else if ("addUser".equals(command)) {
			addUser(request, response);
		} else if ("changeUserInfo".equals(command)) {
			changeUserInfo(request, response);
		} else if ("resetPass".equals(command)) {
			resetPass(request, response);
		} else if ("checkCode".equals(command)) {
			checkCode(request, response);
		} else if("checkPhone".equals(command)){
			checkPhone(request,response);
		} else if("checkEmail".equals(command)){
			checkEmail(request,response);
		} else{
			throw new IllegalStateException("请求非法~");
		}
	}

	/**
	 * 验证邮箱唯一
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void checkEmail(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String email = request.getParameter("email");
		if (StringUtils.isNoneBlank(email)) {
			response.setCharacterEncoding(Constant.ENCODING_UTF8);
			PrintWriter out = null;
			try {
				out = response.getWriter();
				if (sysDao.checkEmail(email)) {
					out.print(1);
				} else {
					out.print(2);
				}
			} finally {
				out.close();
			}
		} else {
			request.getRequestDispatcher("/WEB-INF/view/sys/user/add-user.jsp").forward(request, response);
		}
	}

	/**
	 * 验证电话唯一
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void checkPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String phone = request.getParameter("phone");
		if (StringUtils.isNoneBlank(phone)) {
			response.setCharacterEncoding(Constant.ENCODING_UTF8);
			PrintWriter out = null;
			try {
				out = response.getWriter();
				if (sysDao.checkPhone(phone)) {
					out.print(1);
				} else {
					out.print(2);
				}
			} finally {
				out.close();
			}
		} else {
			request.getRequestDispatcher("/WEB-INF/view/sys/user/add-user.jsp").forward(request, response);
		}
	}

	/**
	 * 检测账号的唯一性
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void checkCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String code = request.getParameter("code");
		if (StringUtils.isNoneBlank(code)) {
			response.setCharacterEncoding(Constant.ENCODING_UTF8);
			PrintWriter out = null;
			try {
				out = response.getWriter();
				if (sysDao.checkCode(code)) {
					out.print(1);
				} else {
					out.print(2);
				}
			} finally {
				out.close();
			}
		} else {
			request.getRequestDispatcher("/WEB-INF/view/sys/user/add-user.jsp").forward(request, response);
		}
	}

	/**
	 * 重置密码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void resetPass(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		sysDao.resetPass(id);
		String password = sysDao.getPassword(id);
		PrintWriter out = null;
		response.setCharacterEncoding(Constant.ENCODING_UTF8);
		try {
			out = response.getWriter();
			if ("123456".equals(password)) {
				out.print("初始密码");
			} else {
				out.print("<a href='javascript:;' onclick='resetPass(${num.count},${user.id});'>重置密码</a>");
			}
		} finally {
			out.close();
		}
	}

	/**
	 * 更改用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void changeUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取参数
		SysUserEntity sysUserEntity = new SysUserEntity();
		String idStr = request.getParameter("id");
		if (StringUtils.isNoneBlank(idStr)) {
			int id = Integer.parseInt(idStr);
			setChangeUserInfoParam(sysUserEntity, request, response);
			LogUtil.i(Constant.LOGGER, sysUserEntity.toString());
			LogUtil.i(Constant.LOGGER, sysUserEntity.toString());
			sysDao.changeUserInfo(sysUserEntity, id);
			SysUserEntity user = sysDao.getUserInfo(id);
			String userJson = FastjsonUtil.toJson(user);
			response.setCharacterEncoding(Constant.ENCODING_UTF8);
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.print(userJson);
			} finally {
				out.close();
			}
		} else {
			throw new IllegalStateException("修改数用户不存在id");
		}

	}

	/**
	 * 设置参数，封装到实体----》更改用户信息
	 * 
	 * @param sysUserEntity
	 * @param request
	 * @param response
	 */
	private void setChangeUserInfoParam(SysUserEntity sysUserEntity, HttpServletRequest request,
			HttpServletResponse response) {
		SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("user");
		if (user != null) {
			sysUserEntity.setId(user.getId());
			String name = request.getParameter("changeName");
			String sexStr = request.getParameter("changeSex");
			String phone = request.getParameter("changePhone");
			String email = request.getParameter("changeEmail");
			String roleIdStr = request.getParameter("changeRole");
			String stateStr = request.getParameter("changeState");
			String memo = request.getParameter("changeMemo");
			sysUserEntity.setName(name);
			sysUserEntity.setPhone(phone);
			sysUserEntity.setEmail(email);
			sysUserEntity.setMemo(memo);

			if (StringUtils.isNoneBlank(sexStr)) {
				sysUserEntity.setSex(Integer.parseInt(sexStr));
			}
			if (StringUtils.isNoneBlank(roleIdStr)) {
				int roleId = Integer.parseInt(roleIdStr);
				sysUserEntity.setRoleId(roleId);
				String className = request.getParameter("className");
				if (roleId == 3 && StringUtils.isNoneBlank(className)) {
					sysUserEntity.setClassId(sysDao.getClassId(className));
				}
			}
			if (StringUtils.isNoneBlank(stateStr)) {
				sysUserEntity.setState(Integer.parseInt(stateStr));
			}
		} else {
			throw new IllegalStateException("请求非法~");
		}
	}

	/**
	 * 添加用户
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void addUser(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("user");
		int operateUserId = user.getId();
		if (operateUserId == 0) {
			response.sendRedirect("/CommonServlet?command=toLogin");
		} else {
			String code = request.getParameter("code");
			String name = request.getParameter("name");
			int sex = Integer.parseInt(request.getParameter("sex"));
			String roleName = request.getParameter("addRoleName");
			String phone = request.getParameter("phone");
			String email = request.getParameter("email");
			String className = request.getParameter("addClassName");
			String addMemo = request.getParameter("addMemo");
			SysUserEntity sysUserEntity = new SysUserEntity();
			sysUserEntity.setCode(code);
			sysUserEntity.setName(name);
			sysUserEntity.setSex(sex);
			if (StringUtils.isNoneBlank(className)) {
				sysUserEntity.setClassId(sysDao.getClassId(className));
			}
			sysUserEntity.setRoleId(sysDao.getRoldId(roleName));
			sysUserEntity.setPhone(phone);
			sysUserEntity.setEmail(email);
			sysUserEntity.setMemo(addMemo);
			sysUserEntity.setOperateUserId(operateUserId);
			sysUserEntity.setOperateTime(new Date());
			LogUtil.d(Constant.LOGGER, "新增用户时的表单数据："+sysUserEntity.toString());
			int row = sysDao.addUser(sysUserEntity);
			if (row == 1) {
				response.sendRedirect(request.getContextPath() + "/user/AllUserCommandServlet?command=splitList");
			} else {
				request.getRequestDispatcher("/WEB-INF/view/sys/user/add-user.jsp").forward(request, response);
			}
		}
	}

	/**
	 * 得到班级信息和角色信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toAddUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<String> classList = sysDao.getClassList();
		List<String> roleList = sysDao.getRoleList();
		request.setAttribute("classList", FastjsonUtil.toJson(classList));
		request.setAttribute("roleList", FastjsonUtil.toJson(roleList));
		request.getRequestDispatcher("/WEB-INF/view/sys/user/add-user.jsp").forward(request, response);
	}

	/**
	 * 得到学生的信息
	 * 
	 * @param request
	 * @param response
	 */
	private void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
		String idStr = request.getParameter("id");
		if (StringUtils.isNoneBlank(idStr)) {
			int id = Integer.parseInt(idStr);
			SysUserEntity sysUserEntity = sysDao.getUserInfo(id);
			LogUtil.i(Constant.LOGGER, sysUserEntity.toString());
			String jsonObj = FastjsonUtil.toJson(sysUserEntity);
			response.setCharacterEncoding(Constant.ENCODING_UTF8);
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.print(jsonObj);
			} catch (IOException e) {
				LogUtil.e(Constant.LOGGER, "获取用户资料IO出错", e);
			} finally {
				out.close();
			}
		}
	}

	/**
	 * 改变用户状态
	 * 
	 * @param request
	 * @param response
	 */
	private void changeState(HttpServletRequest request, HttpServletResponse response) {
		String idStr = request.getParameter("id");
		int state = 1;// 有效
		response.setCharacterEncoding(Constant.ENCODING_UTF8);
		if (StringUtils.isNoneBlank(idStr) && !"0".equals(idStr)) {
			int id = Integer.parseInt(idStr);
			int dBstate = sysDao.geStateById(id);
			if (dBstate == state) {
				state = 2;
			}
			sysDao.changeState(state, id);
			state = sysDao.geStateById(id);
			PrintWriter out = null;
			try {
				out = response.getWriter();
				if (state == 2) {
					out.print("无效");
				} else {
					out.print("有效");
				}
			} catch (IOException e) {
				LogUtil.e(Constant.LOGGER, "用户状态修改响应IO异常", e);
			} finally {
				out.close();
			}
		}
	}

	/**
	 * 用户查询（所有） 带分页带条件
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void splitList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pageNo = Constant.DEFAULT_PAGE_NO;
		int pageSize = Constant.DEFAULT_PAGE_SIZE;

		String pageNoStr = request.getParameter("pageNo");
		String pageSizeStr = request.getParameter("pageSize");
		SearchCondition searchConidtion = new SearchCondition();
		initConditionUserEntity(request, response, searchConidtion);
		LogUtil.printObject(searchConidtion);
		if (StringUtils.isNoneBlank(pageNoStr)) {
			pageNo = Integer.parseInt(pageNoStr);
		}
		if (StringUtils.isNoneBlank(pageSizeStr)) {
			pageSize = Integer.parseInt(pageSizeStr);
		}
		LogUtil.i(Constant.LOGGER, "pageNo=" + pageNo);
		LogUtil.i(Constant.LOGGER, "pageSize=" + pageSize);
		PageModel<SysUserEntity> pageModel = sysDao.listSplitAll(pageNo, pageSize, searchConidtion);
		// 转向
		request.setAttribute("researchInfo", searchConidtion);
		request.setAttribute("classListJson", FastjsonUtil.toJson(searchConidtion.getClassList()));
		request.setAttribute("pageModel", pageModel);
		request.getRequestDispatcher("/WEB-INF/view/sys/user/user-list.jsp").forward(request, response);

	}

	/**
	 * 将条件查询的条件封装到实体
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	private void initConditionUserEntity(HttpServletRequest request, HttpServletResponse response,
			SearchCondition sysUserEntity) {
		String nameStr = request.getParameter("name");
		String roleNameStr = request.getParameter("roleName");
		String classNameStr = request.getParameter("className");
		if (StringUtils.isNoneBlank(nameStr)) {
			sysUserEntity.setName(nameStr);
		}
		if (StringUtils.isNoneBlank(roleNameStr)) {
			sysUserEntity.setRoleName(roleNameStr);
		}
		if (StringUtils.isNoneBlank(classNameStr)) {
			sysUserEntity.setClassName(classNameStr);
		}

		String stateStr = request.getParameter("state");
		if ("有效".equals(StringUtils.trim(stateStr))) {
			sysUserEntity.setState(1);
		} else if ("无效".equals(StringUtils.trim(stateStr))) {
			sysUserEntity.setState(2);
		}
		sysUserEntity.setClassList(sysDao.getClassList());
		sysUserEntity.setRoleList(sysDao.getRoleList());
	}
}
